using MediatR;
using Microsoft.EntityFrameworkCore;
using WeatherHistory.Data.Repositories.Interfaces;

namespace WeatherHistory.Api.CommandsQueries.Queries.Regions.Search;

public class SearchRegionsQueryHandler : IRequestHandler<SearchRegionsQueryRequest, SearchRegionsQueryResponse>
{
    private readonly IRegionRepository _regionRepository;

    public SearchRegionsQueryHandler(IRegionRepository regionRepository)
    {
        _regionRepository = regionRepository;
    }

    public async Task<SearchRegionsQueryResponse> Handle(SearchRegionsQueryRequest request, CancellationToken cancellationToken)
    {
        var response = new SearchRegionsQueryResponse();

        var weatherRegionRelationsQuery = _regionRepository.AsQueryable();

        response.Items = await weatherRegionRelationsQuery
            .Skip(request.From)
            .Take(request.Size)
            .Select(x => new SearchRegionsQueryRegionDto
            {
                Id = x.Id,
                name = x.Name,
                ParrentRegionId = x.ParentRegionId
            })
            .ToListAsync(cancellationToken);

        return response;
    }
}